import React, { useEffect, useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';

interface WordData {
  id: number;
  word: string;
  accent: string;
  mean_cn: string;
  sentence: string;
  sentence_trans: string;
  word_etyma: string;
}

const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:8000';

const Study: React.FC = () => {
  const [wordData, setWordData] = useState<WordData | null>(null);
  const [readSentence, setReadSentence] = useState(false);
  const [loop, setLoop] = useState(false);
  const [speed, setSpeed] = useState(1.0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [autoPlay, setAutoPlay] = useState(false);
  const [hasStartedAutoPlay, setHasStartedAutoPlay] = useState(false);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const isFirstRender = useRef(true);
  const navigate = useNavigate();

  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      fetchCurrentWord();
    }
  }, []);

  useEffect(() => {
    if (wordData && autoPlay && hasStartedAutoPlay && !isPlaying && !isPaused) {
      playAudio();
    }
  }, [wordData, autoPlay, hasStartedAutoPlay, isPaused]);

  const fetchCurrentWord = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const response = await fetch(`${API_BASE}/current-word`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        },
      });
      
      if (response.status === 401) {
        localStorage.removeItem('token');
        navigate('/login');
        return;
      }
      
      const result = await response.json();
      if (result.code !== 200) {
        setError(result.msg || "获取单词失败");
        return;
      }

      setWordData(result.data);
    } catch (error) {
      console.error("获取单词失败:", error);
      setError(error instanceof Error ? error.message : "获取单词失败");
    } finally {
      setIsLoading(false);
    }
  };

  const fetchNextWord = async () => {
    try {
      const response = await fetch(`${API_BASE}/next-word`, {
        method: "POST",
        headers: { 
          Authorization: `Bearer ${localStorage.getItem('token')}` 
        },
      });
      
      if (response.status === 401) {
        localStorage.removeItem('token');
        navigate('/login');
        return;
      }
      
      const result = await response.json();
      if (result.code !== 200) {
        alert(result.msg || '获取下一个单词失败');
        return;
      }

      setWordData(result.data);
    } catch (error) {
      console.error("获取下一个单词失败:", error);
      alert(error instanceof Error ? error.message : "获取下一个单词失败");
    }
  };

  const previousWord = async () => {
    try {
      const response = await fetch(`${API_BASE}/previous-word`, {
        headers: { 
          Authorization: `Bearer ${localStorage.getItem('token')}` 
        },
      });
      
      if (response.status === 401) {
        localStorage.removeItem('token');
        navigate('/login');
        return;
      }
      
      const result = await response.json();
      if (result.code !== 200) {
        alert(result.msg || '获取上一个单词失败');
        return;
      }

      setWordData(result.data);
    } catch (error) {
      console.error("获取上一个单词失败:", error);
      alert(error instanceof Error ? error.message : "获取上一个单词失败");
    }
  };

  const playAudio = async () => {
    if (!wordData || isPlaying) return;
    setIsPlaying(true);
    setIsPaused(false);

    // 创建所有需要播放的音频
    const wordUrl = `${API_BASE}/pronounce?text=${encodeURIComponent(wordData.word)}`;
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
    }
    const wordAudio = new Audio(wordUrl);
    const meanAudio = new Audio(`${API_BASE}/pronounce-cn?text=${encodeURIComponent(wordData.mean_cn)}`);
    const sentenceAudio = new Audio(`${API_BASE}/pronounce?text=${encodeURIComponent(wordData.sentence)}`);
    const sentenceTransAudio = new Audio(`${API_BASE}/pronounce-cn?text=${encodeURIComponent(wordData.sentence_trans)}`);

    const playSequence = () => {
      // 播放单词
      wordAudio.play().then(() => {
        // 单词播放完成后播放中文释义
        wordAudio.addEventListener('ended', () => {
          meanAudio.play().then(() => {
            // 中文释义播放完成后，如果开启了朗读句子，则播放句子
            meanAudio.addEventListener('ended', () => {
              if (readSentence && wordData.sentence) {
                sentenceAudio.play().then(() => {
                  // 句子播放完成后播放中文翻译
                  sentenceAudio.addEventListener('ended', () => {
                    sentenceTransAudio.play().then(() => {
                      // 中文翻译播放完成后，如果开启了循环播放，则重新开始
                      sentenceTransAudio.addEventListener('ended', () => {
                        if (loop) {
                          playSequence();
                        } else {
                          setIsPlaying(false);
                          if (autoPlay && !isPaused) {
                            fetchNextWord();
                          }
                        }
                      }, { once: true });
                    }).catch(() => {
                      setIsPlaying(false);
                      if (autoPlay && !isPaused) {
                        fetchNextWord();
                      }
                    });
                  }, { once: true });
                }).catch(() => {
                  setIsPlaying(false);
                  if (autoPlay && !isPaused) {
                    fetchNextWord();
                  }
                });
              } else {
                // 如果没有开启朗读句子，则检查是否需要循环播放
                if (loop) {
                  playSequence();
                } else {
                  setIsPlaying(false);
                  if (autoPlay && !isPaused) {
                    fetchNextWord();
                  }
                }
              }
            }, { once: true });
          }).catch(() => {
            setIsPlaying(false);
            if (autoPlay && !isPaused) {
              fetchNextWord();
            }
          });
        }, { once: true });
      }).catch(() => {
        setIsPlaying(false);
        if (autoPlay && !isPaused) {
          fetchNextWord();
        }
      });
    };

    const onCanPlay = () => {
      wordAudio.playbackRate = speed;
      meanAudio.playbackRate = speed;
      sentenceAudio.playbackRate = speed;
      sentenceTransAudio.playbackRate = speed;
    };

    wordAudio.addEventListener("canplay", onCanPlay);
    meanAudio.addEventListener("canplay", onCanPlay);
    sentenceAudio.addEventListener("canplay", onCanPlay);
    sentenceTransAudio.addEventListener("canplay", onCanPlay);

    // 保存当前音频引用
    audioRef.current = wordAudio;

    // 开始播放
    playSequence();
  };

  const handlePlayPause = () => {
    if (isPlaying) {
      if (audioRef.current) {
        audioRef.current.pause();
      }
      setIsPlaying(false);
      setIsPaused(true);
    } else {
      if (isPaused) {
        setIsPaused(false);
      }
      setHasStartedAutoPlay(true);
      playAudio();
    }
  };

  const handleAutoPlayChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setAutoPlay(e.target.checked);
    setIsPaused(false);
    if (e.target.checked) {
      setHasStartedAutoPlay(false);
    }
  };

  if (isLoading) {
    return <div className="loading">加载中...</div>;
  }

  if (error) {
    return (
      <div className="error-container">
        <div className="error-message">{error}</div>
        <button 
          className="select-book-btn"
          onClick={() => navigate('/books')}
        >
          选择书本
        </button>
      </div>
    );
  }

  if (!wordData) {
    return null;
  }

  return (
    <div className="study-container">
      <button 
        className="back-to-books-btn"
        onClick={() => navigate('/books')}
      >
        重新选择书本
      </button>
      <div className="word-card">
        <div className="controls">
          <label className="switch-label">
            <input
              type="checkbox"
              checked={readSentence}
              onChange={(e) => setReadSentence(e.target.checked)}
            />
            朗读句子
          </label>
          <label className="switch-label">
            <input
              type="checkbox"
              checked={loop}
              onChange={(e) => setLoop(e.target.checked)}
            />
            循环播放
          </label>
          <label className="switch-label">
            <input
              type="checkbox"
              checked={autoPlay}
              onChange={handleAutoPlayChange}
            />
            自动播放
          </label>
          <select value={speed} onChange={(e) => setSpeed(Number(e.target.value))}>
            <option value={0.5}>0.5x 倍速</option>
            <option value={0.75}>0.75x 倍速</option>
            <option value={1.0}>1.0x 倍速</option>
            <option value={1.25}>1.25x 倍速</option>
            <option value={1.5}>1.5x 倍速</option>
          </select>
        </div>
        <div className="word">{wordData.word}</div>
        <div className="phonetic">{wordData.accent}</div>
        <div className="definition">{wordData.mean_cn}</div>
        {readSentence && wordData.sentence && (
          <div className="sentence-container">
            <div className="sentence">{wordData.sentence}</div>
            <div className="sentence-trans">{wordData.sentence_trans}</div>
          </div>
        )}
        <button className="play-btn" onClick={handlePlayPause}>
          {isPlaying ? "暂停" : isPaused ? "继续" : "播放"}
        </button>
        <div className="navigation-buttons">
          <button className="nav-btn prev-btn" onClick={previousWord}>
            上一个
          </button>
          <button className="nav-btn next-btn" onClick={fetchNextWord}>
            下一个
          </button>
        </div>
      </div>
    </div>
  );
};

export default Study; 